var backbone = require('backbone'),
    _ = require('underscore'),
    validation = require('backbone-validation'),
   user_model = require('../models/User_Model');


/*On enregistre le username en bdd après avoir effectué la Validation*/
exports.addUser = function(req, res, db) {
   
    username = req.body.username;
    mail = req.body.mail;
    password = req.body.password;
    confirmpassword = req.body.confirmpassword;
    
    //On autorise la validation coté
     _.extend(backbone.Model.prototype, validation.mixin);

    var user = new user_model.User({'username' : username,'mail' : mail, 'password' : password, 'confirmpassword' : confirmpassword});

    //On force la validation
    var isValid = user.isValid(true);

    //On valide le model
    var validate = user.validate();
    console.log(validate);
    if(!isValid)
    {
        res.send(validate);
    }
    else
    {
        //On vérifie si l'username n'existe pas déja
        checkUsernameFree(db, username,  function(error){

            if(error)
            {
                console.log(error);
                res.send(error);
            }
            else
            {
                //On récupère le model User
                var userdb =  new db.User;

                userdb.username = user.getUsername();
                userdb.mail = user.getMail();
                userdb.password = user.getPassword();

                userdb.save(function (err, user) {
                    if (err) throw err; 
                    console.log('User saved');  
                    console.log(user);
                    res.send(user);
                });
            } 
        });
    }
};

checkUsernameFree = function(db,username, callback)
{
    db.User.find({'username' : username}, function(err, result) {
        if (!err){
           var error = null; 
           if(result.length>0)
           {
                 console.log(result);
                 error = {"username" : "Ce Pseudo est déja utilisé"};
            }

            callback(error);
        }
        else { throw err;}
    });
};

exports.findAll = function(req, res, models) {
    console.log("On est dans la méthode findAll");
    models.User.find({}, function(err, users) {
            if (!err){ 
                res.send(users);
            }
            else { throw err;}

            }
    );
};


exports.checkLogin = function(req, res, models)
{
    console.log("On est dans la méthode findByUserName");
    var username = req.body.username;
    var password = req.body.password;
    models.User.find({"username" : username}, function(err, result) {
            if (!err){ 
               if(result.length>0)
               {
                    if(result.password !=  password)
                    {
                        error = {"password" : "Combinaison Login/Password invalide"};
                        res.send(error);
                    }
                    else
                    {
                        res.send(result);
                    }
               }
               else
               {
                     error = {"username" : "Ce Login n'existe pas"};
                     res.send(error);
               }
            }
            else { throw err;}

            }
    );
}

/*exports.updateWine = function(req, res) {
    var id = req.params.id;
    var wine = req.body;
    delete wine._id;
    console.log('Updating wine: ' + id);
    console.log(JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(id)}, wine, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating wine: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(wine);
            }
        });
    });
}

exports.deleteWine = function(req, res) {
    var id = req.params.id;
    console.log('Deleting wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(req.body);
            }
        });
    });
}*/
